package entity;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import util.DBUtil;
import util.Validator;

public class User {

	public String name;
	
	public String pwd;
	
	public String type;

	public String note;

	public boolean login(String userName, String password) {
		String sql = "select name, pwd, type, note from pm_user where name = ? and pwd = ?";
		String[] paraArray = {userName,password};
		try {
			String[] record= DBUtil.queryOne(sql, paraArray, 4);
			if(record == null){
				return false;
			}
			this.name = record[0];
			this.pwd = record[1];
			this.type = record[2];
			this.note = record[3];
			return true;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public boolean save() {
		String sql = "insert into pm_user(name, pwd, type, note) values (?,?,?,?)";
		String[] paraArray = {name,pwd,type,note};
		try {
			int count = DBUtil.update(sql, paraArray);
			return count > 0;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public boolean updatePwd() {
		String sql = "update pm_user set pwd = ? where name = ?";
		String[] paraArray = {pwd,name};
		try {
			int count = DBUtil.update(sql, paraArray);
			return count > 0;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return false;
	}

	public List<String[]> query(String[] params) {
		List<Object> list = new ArrayList<>();
		String sql = "select name, type, note from pm_user where true ";
		if(Validator.isNotEmpty(params[0])){
			sql += "and name = ?";
			list.add(params[0]);
		}
		try {
			List<String[]> records = DBUtil.query(sql, list.toArray(), 3);
			return records;
		} catch (SQLException e) {
			DBUtil.error(e);
		}
		return new ArrayList<String[]>();
	}

}
